import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

void main() {
  runApp(const TodoApp());
}

class TodoApp extends StatelessWidget {
  const TodoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '待办清单',
      theme: ThemeData(
        primarySwatch: Colors.indigo,
        brightness: Brightness.light,
        visualDensity: VisualDensity.adaptivePlatformDensity,
        cardTheme: CardTheme(
          elevation: 4,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        ),
        floatingActionButtonTheme: FloatingActionButtonThemeData(
          backgroundColor: Colors.indigo,
        ),
      ),
      home: const TodoHomePage(),
    );
  }
}

// 待办事项类
class TodoItem {
  String title;
  bool isCompleted;
  final DateTime createdAt;

  TodoItem({
    required this.title,
    this.isCompleted = false,
    DateTime? createdAt,
  }) : createdAt = createdAt ?? DateTime.now();

  // 转换为JSON
  Map<String, dynamic> toJson() => {
        'title': title,
        'isCompleted': isCompleted,
        'createdAt': createdAt.toIso8601String(),
      };

  // 从JSON创建
  factory TodoItem.fromJson(Map<String, dynamic> json) => TodoItem(
        title: json['title'],
        isCompleted: json['isCompleted'],
        createdAt: DateTime.parse(json['createdAt']),
      );
}

class TodoHomePage extends StatefulWidget {
  const TodoHomePage({super.key});

  @override
  _TodoHomePageState createState() => _TodoHomePageState();
}

// 动画配置
const Duration _animationDuration = Duration(milliseconds: 300);

class _TodoHomePageState extends State<TodoHomePage> {
  final List<TodoItem> _todos = [];
  final TextEditingController _textEditingController = TextEditingController();
  bool _isLoading = true;
  bool _isAddingTodo = false;

  @override
  void initState() {
    super.initState();
    _loadTodos();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '待办清单',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        elevation: 4,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(16)),
        ),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _textEditingController,
                        decoration: InputDecoration(
                          labelText: '添加新的待办事项',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          prefixIcon: Icon(Icons.add_task_outlined),
                        ),
                        onSubmitted: _addTodo,
                        textInputAction: TextInputAction.done,
                      ),
                    ),
                    SizedBox(width: 8),
                    ElevatedButton(
                      onPressed: () => _addTodo(_textEditingController.text),
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      child: Icon(Icons.add),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _todos.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.check_circle_outline, size: 64, color: Colors.grey),
                            SizedBox(height: 16),
                            Text(
                              '没有待办事项',
                              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                            ),
                            SizedBox(height: 8),
                            Text(
                              '添加一些新的任务开始使用吧！',
                              style: TextStyle(color: Colors.grey),
                            ),
                          ],
                        ),
                      )
                    : AnimatedList(
                        initialItemCount: _todos.length,
                        itemBuilder: (context, index, animation) {
                          final todo = _todos[index];
                          return SizeTransition(
                            sizeFactor: animation,
                            child: FadeTransition(
                              opacity: animation,
                              child: Card(
                                margin: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                                child: ListTile(
                                  title: Text(
                                    todo.title,
                                    style: todo.isCompleted
                                        ? TextStyle(
                                            decoration: TextDecoration.lineThrough,
                                            color: Colors.grey,
                                          )
                                        : TextStyle(fontWeight: FontWeight.w500),
                                  ),
                                  subtitle: Text(
                                    '创建于: ${todo.createdAt.toLocal().toString().substring(0, 16)}',
                                    style: TextStyle(fontSize: 12, color: Colors.grey),
                                  ),
                                  leading: Checkbox(
                                    value: todo.isCompleted,
                                    onChanged: (bool? value) {
                                      setState(() {
                                        todo.isCompleted = value ?? false;
                                      });
                                      _saveTodos();
                                    },
                                    activeColor: Colors.indigo,
                                  ),
                                  trailing: IconButton(
                                    icon: Icon(Icons.delete_outline, color: Colors.red),
                                    onPressed: () {
                                      // 移除动画
                                      final removedTodo = _todos[index];
                                      setState(() {
                                        _todos.removeAt(index);
                                      });
                                      _saveTodos();
                                    },
                                    tooltip: '删除',
                                  ),
                                  onTap: () {
                                    setState(() {
                                      todo.isCompleted = !todo.isCompleted;
                                    });
                                    _saveTodos();
                                  },
                                ),
                              ),
                            ),
                          );
                        },
                      ),
          ),
        ],
      ),
    );
  }

  Future<void> _loadTodos() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final todosJson = prefs.getString('todos');
      
      if (todosJson != null) {
        final List<dynamic> todosList = jsonDecode(todosJson);
        setState(() {
          _todos.clear();
          _todos.addAll(todosList.map((item) => TodoItem.fromJson(item)));
        });
      }
    } catch (e) {
      print('加载待办事项失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _saveTodos() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final todosJson = jsonEncode(_todos.map((todo) => todo.toJson()).toList());
      await prefs.setString('todos', todosJson);
    } catch (e) {
      print('保存待办事项失败: $e');
    }
  }

  void _addTodo(String title) {
    if (title.trim().isNotEmpty) {
      final newTodo = TodoItem(title: title.trim());
      setState(() {
        _todos.add(newTodo);
        _textEditingController.clear();
        _isAddingTodo = true;
      });
      _saveTodos();
      
      // 显示添加成功的提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('待办事项已添加'),
          duration: Duration(seconds: 2),
          action: SnackBarAction(
            label: '撤销',
            onPressed: () {
              setState(() {
                _todos.remove(newTodo);
              });
              _saveTodos();
            },
          ),
        ),
      );
    }
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }
}
